package org.raymond.iworks.study.netty.atguigu.nio;

import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

@Slf4j
public class NioServer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector sel = Selector.open();
        ssc.bind(new InetSocketAddress(6666));
        ssc.register(sel, SelectionKey.OP_ACCEPT);
        while(true){
            if(0==sel.select(5000)){
                log.info("服务器等待了5秒");
                continue;
            }
            Set<SelectionKey> keys = sel.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while(it.hasNext()){
                SelectionKey key = it.next();
                if(key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    log.info("收到一个新的连接:{}", sc.hashCode());
                    sc.configureBlocking(false);
                    sc.register(sel, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if(key.isReadable()){
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer byteBuffer = (ByteBuffer)key.attachment();
                    int read = sc.read(byteBuffer);
                    if(read!=-1) {
                        log.info("收到数据:{}", new String(byteBuffer.array()).trim());
                    }else{
                        sc.close();
                    }
                }
                it.remove();
            }
        }
    }
}
